﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Interpreter.BuiltIns
{
	internal class GameImage : Module
	{
		public override void Register(FunctionRegistry registry)
		{
			registry.Register(4, new GameImageCtorSize());
			registry.Register(20, new GameImageCtorFile());
			registry.Register(24, new GameImageFill());
		}

		private class GameImageCtorFile : NativeFunction
		{
			public override Value Do(StackContext stackContext, Value[] args)
			{
				// TODO: rewrite this
				string path = args[0].Value0.ToString();
				GameCore.Image img;
				if (path.StartsWith("$"))
				{
					// TODO: embedded file resource
					return Value.Null;
				}
				else
				{
					string fullPath = System.IO.Path.Combine(stackContext.Metadata.ProgramRoot, path);
					img = new GameCore.Image(fullPath, true);
				}
				
				return new Value(Value.TYPE_LIST, new Value[]
				{
					new Value(Value.TYPE_NATIVE_OBJECT, img),
					Value.GetInteger(img.Width),
					Value.GetInteger(img.Height)
				}, 3);
			}
		}

		private class GameImageFill : NativeFunction
		{
			public override Value Do(StackContext stackContext, Value[] args)
			{
				Value[] fillArgs = stackContext.Args;
				int r = (int)fillArgs[0].Value0 & 255;
				int g = (int)fillArgs[1].Value0 & 255;
				int b = (int)fillArgs[2].Value0 & 255;
				int a = (int)fillArgs[3].Value0 & 255;
				GameCore.Image image = (GameCore.Image)args[0].Value0;
				image.Fill(r, g, b, a);

				return Value.Null;
			}
		}

		private class GameImageCtorSize : NativeFunction
		{
			public override Value Do(StackContext stackContext, Value[] args)
			{
				int width = (int)args[0].Value0;
				int height = (int)args[1].Value0;

				GameCore.Image img = new GameCore.Image(width, height);

				return new Value(Value.TYPE_LIST, new Value[]
				{
					new Value(Value.TYPE_NATIVE_OBJECT, img),
					Value.GetInteger(width),
					Value.GetInteger(height)
				}, 3);
			}
		}
	}
}
